﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IOT4Week1Day1.App.Dtos;
using IOT4Week1Day1.Domain.IRepositories;
using IOT4Week1Day1.Domain.Models;

namespace IOT4Week1Day1.App
{
    /// <summary>
    /// 商品模块服务
    /// </summary>
    public class ProductAppService
    {
        //1. 注入什么？   IRepository<Product>怎么读？  Product的仓储
        private readonly IRepository<Product> _productRepository;
        private readonly IRepository<ProductType> _productTypeRepository;

        public ProductAppService(IRepository<Product> productRepository,
                                 IRepository<ProductType> productTypeRepository)
        {
            _productRepository = productRepository;
            _productTypeRepository = productTypeRepository;
        }

        //2.写分页方法
        /// <summary>
        /// 商品分页
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="title">商品标题模糊条件</param>
        /// <param name="typeId">商品分类Id   (int可空类型)</param>
        /// <param name="status">上下架状态</param>
        /// <returns></returns>
        public PagedList<ProductDto> GetPage(int pageIndex, int pageSize, string title, int? typeId, int? status)
        {
            // 拼接查询语句 （sql语句）
            var query = from a in _productRepository.GetTable()
                        join b in _productTypeRepository.GetTable()  //联查
                        on a.TypeId equals b.Id                      //联查条件
                        where (string.IsNullOrEmpty(title) || a.Title.Contains(title))  //筛选条件
                           && (typeId == null || a.TypeId == typeId)
                           && (status == null || a.Status == status)
                        orderby a.Id descending
                        select new ProductDto
                        {
                            Id = a.Id,
                            Title = a.Title,
                            Status=a.Status,
                            Tname = b.Tname,
                            TypeId = a.TypeId
                        };

            PagedList<ProductDto> result = new PagedList<ProductDto>();
            result.PagedData = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); //执行SQL语句
            result.TotalCount = query.Count();  //执行select count(*)语句

            return result;
        }

    }
}
